<script setup>
import {
  getListAPI,
  AddDataAPI,
  DetailDataAPI,
  EditDataAPI,
  submitAPI,
  deleteReviewAPI,
  productPlanReviewAPI,
  terminateAPI,
  addWipAPI,
  DelDataAPI,
  semiFinishedProductAPI,
  pushAPI
} from '@/api/order/producManaga/producManaga.js'

//表单组件
import From from './form.vue'
import End from './end.vue'

//代理
const { proxy } = getCurrentInstance()

// 封装 方法 字典查询
const {
  plan_status, // 单据状态
  is_push_status
} = proxy.useDict('plan_status', 'is_push_status')

/**
 * 表单ref
 */
const formRef = ref(null)
const endRef = ref(null)

/**
 * 新增弹窗
 */
const isShow = ref(false)

/**
 * 审核弹窗
 */
const examineIsShow = ref(false)
const endIsShow = ref(false)

/**
 * 标题
 */
const title = ref('新增')

// 保存加载状态
const Btnloading = ref(false)

// 表格加载状态
const loading = ref(false)

// 表格数据
const TableData = ref([])

// 表格数据
const TableDataTwo = ref([])

// 列表总数量
const total = ref(0)

// 是否禁用删除
const DelDisabled = ref(false)

// 是否禁用 单选
const ExamineDisabled = ref(false)

// 按钮加载
const BtnLoading = ref(false)

// 是否禁用表单输入
const disabled = ref(false)

// 表格勾选数据
const Ids = ref([])
const rows = ref([])

// 查询条件
const SelectList = ref([
  { type: '日期范围' },
  { label: '销售订单', model: 'salesOrderNum', type: '输入框' },
  { label: '计划单号', model: 'planNumber', type: '输入框' },
  { label: '物料编码', model: 'materialCode', type: '输入框' },
  { label: '规格型号', model: 'specType', type: '输入框' },
  { label: '单据状态', model: 'documentStatus', type: '下拉单选', opt: plan_status },
  { label: '推送状态', model: 'isPushStatus', type: '下拉单选', opt: is_push_status }
])

// 新增字段modeling
const ruleForm = ref({})

// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 50,
  planType: '1' //  1 生产计划 2 样品计划
})

/**
 * 弹窗
 */

// 创建生产计划 弹窗
const isConfirm = async () => {
  title.value = '创建生产计划'
  isShow.value = true
}

// 修改 弹窗
const edit = async val => {
  try {
    const { data: res } = await DetailDataAPI(val.id)
    Object.keys(res).forEach(item => (ruleForm.value[item] = res[item]))
    title.value = '修改'
    isShow.value = true
  } catch (error) {}
}

// 查看 弹窗
const dxamine = async val => {
  try {
    const { data: res } = await DetailDataAPI(val.id)
    Object.keys(res).forEach(item => (ruleForm.value[item] = res[item]))
    ruleForm.value.planNumber = val.planNumber
    title.value = '查看'
    examineIsShow.value = true
  } catch (error) {}
}

/**
 * 审核计划
 * @param
 */
const auditPlan = async () => {
  // if (rows.value[0].documentStatus == 3) return proxy.warningMsg('已审核')
  try {
    const { data: res } = await DetailDataAPI(Ids.value[0])
    Object.keys(res).forEach(item => (ruleForm.value[item] = res[item]))
    title.value = '审核计划'
    examineIsShow.value = true
  } catch (error) {}
}

// 保存按钮
const submit = () => {
  if (title.value == '创建生产计划') confirm()
  if (title.value == '修改') editSub()
}

// 新增
const confirm = async () => {
  try {
    const isIf = await formRef.value.submit()
    if (!isIf) return
    BtnLoading.value = true
    await AddDataAPI(isIf)
    proxy.successMsg('新增成功')
    close()
    getList()
  } catch {
  } finally {
    BtnLoading.value = false
  }
}

/**
 * 修改
 */
const editSub = async () => {
  try {
    const isIf = await formRef.value.submit()
    if (!isIf) return
    BtnLoading.value = true
    await EditDataAPI(isIf)
    proxy.successMsg('修改成功')
    close()
    getList()
  } catch {
  } finally {
    BtnLoading.value = false
  }
}

/**
 * 删除
 */
const del = async val => {
  try {
    const MesBox = await proxy.FreezMessageBox('是否确定删除？')
    if (!MesBox) return
    await DelDataAPI({ idStr: val.id })
    proxy.successMsg('删除成功')
    getList()
  } catch (error) {}
}

// 计划终止
const isTheEnd = async () => {
  const isif = rows.value.every(item => item.documentStatus != 6)
  if (!isif) return proxy.warningMsg('该单已处于终止状态！')
  endIsShow.value = true
  title.value = '终止'
  //  await terminateAPI({ idStr: Ids.value[0] })
}

/**
 * 终止确认
 * @param val
 *
 */
const endSubmit = async () => {
  const result = await endRef.value.submit()
  if (!result) return
  Btnloading.value = true
  try {
    await terminateAPI({ idStr: Ids.value.join(','), terminationReason: result.terminationReason })
    getList()
    close()
    proxy.successMsg('终止成功！')
  } catch (err) {
    console.error(err)
  } finally {
    Btnloading.value = false
  }
}

// 审核计划提交
const yesAndNo = async val => {
  const result = await formRef.value.submit()
  if (!result) return
  Btnloading.value = true
  try {
    await productPlanReviewAPI({
      idStr: result.id,
      isAdopt: val,
      reviewComments: result.auditOpinion
    })
    getList()
    close()
    proxy.successMsg('审核成功！')
  } catch (err) {
    console.error(err)
  } finally {
    Btnloading.value = false
  }
}

/**
 * 提交审核按钮
 */
const examineSub = async () => {
  try {
    const isif = rows.value.every(item => item.documentStatus == 1)
    if (!isif) return proxy.warningMsg('此操作仅为已创建状态可用！')
    const MesBox = await proxy.FreezMessageBox('是否确定提交审核？')
    if (!MesBox) return
    const res = await submitAPI({ idStr: Ids.value.join(',') })
    if (res.code !== 200) return (BtnLoading.value = false)
    proxy.successMsg('操作成功')
    getList()
  } catch (error) {}
}

/**
 * 批量审核
 */
const allExamine = async () => {
  const is = rows.value.every(t => ['2', '3'].includes(t.documentStatus))
  if (!is) return proxy.warningMsg('只有待审核和审核中的数据可操作!')
  const num = rows.value.length
  const MesBox = await proxy.FreezMessageBox1(`共${num}条审核订单`)
  if (MesBox) {
    await productPlanReviewAPI({
      idStr: Ids.value.join(','),
      isAdopt: '1'
    })
    getList()
  } else {
    await productPlanReviewAPI({
      idStr: Ids.value.join(','),
      isAdopt: '2'
    })
    getList()
  }
}

/**
 * 撤销审核
 */
const revokeReview = async () => {
  try {
    const MesBox = await proxy.FreezMessageBox('是否确定撤销审核？')
    if (!MesBox) return
    await deleteReviewAPI(Ids.value[0])
    proxy.successMsg('操作成功')
    getList()
  } catch (error) {}
}

/**
 * 生成完工入库单
 */
const getrkd = async () => {
  try {
    const MesBox = await proxy.FreezMessageBox('是否确定生成完工入库单？')
    if (!MesBox) return
    await addWipAPI({ idStr: Ids.value.join(',') })
    proxy.successMsg('操作成功')
    getList()
  } catch (error) {}
}

/**
 * 生成半成品入库单
 */
const getFinished = async () => {
  try {
    const MesBox = await proxy.FreezMessageBox('是否确定生成半成品入库单？')
    if (!MesBox) return
    await semiFinishedProductAPI({ idStr: Ids.value.join(',') })
    proxy.successMsg('操作成功')
    getList()
  } catch (error) {}
}

/**
 * 推送
 */
const pushData = async () => {
  proxy.$modal.loading('请稍候...')
  try {
    await pushAPI({ idStr: Ids.value.join(',') })
    proxy.successMsg('推送成功')
    getList()
  } catch (error) {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 弹窗关闭时
const close = () => {
  isShow.value = false
  examineIsShow.value = false
  endIsShow.value = false
  ruleForm.value = {}
}

// 销售计划 列表选中 及 判断是否禁用删除 || 修改
const salesPlanChange = selection => {
  rows.value = selection
  Ids.value = selection.map(item => item.id)
  DelDisabled.value = !selection.length
  selection.length <= 0 || selection.length > 1 ? (ExamineDisabled.value = true) : (ExamineDisabled.value = false)
}
salesPlanChange([])

// 样品计划 列表选中 及 判断是否禁用删除 || 修改
const samplePlanChange = selection => {
  rows.value = selection
  Ids.value = selection.map(item => item.id)
  DelDisabled.value = !selection.length
  selection.length <= 0 || selection.length > 1 ? (ExamineDisabled.value = true) : (ExamineDisabled.value = false)
}
samplePlanChange([])

// 查询条件提交
const selectSubmit = Obj => {
  for (let Key in Obj) {
    query[Key] = Obj[Key]
  }
  getList()
}

// 获取列表
const getList = async () => {
  try {
    loading.value = true
    const res = await getListAPI(query)
    total.value = res.total
    TableData.value = res.rows
  } catch {
  } finally {
    loading.value = false
  }
}
getList()

/**
 * tabs改变事件
 */
const tabChange = val => {
  TableData.value = []
  getList()
}

const tableHeight = ref(0)

const maxHeight = computed(() => {
  const windowHeight = window.innerHeight
  const headerHeight = 380
  const paginationHeight = 0
  return windowHeight - headerHeight - paginationHeight
})

const handleResize = () => {
  tableHeight.value = maxHeight.value
}

onMounted(() => {
  tableHeight.value = maxHeight.value
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <SelectForm :SelectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card>
      <el-button type="primary" v-hasPermi="['order:producManaga:producPlan:add']" @click="isConfirm">创建</el-button>
      <el-button
        type="danger"
        v-hasPermi="['order:producManaga:producPlan:stop']"
        :disabled="ExamineDisabled"
        @click="isTheEnd"
        >终止</el-button
      >
      <el-button
        type="warning"
        v-hasPermi="['order:producManaga:producPlan:examine']"
        :disabled="DelDisabled"
        @click="examineSub"
        >提交审核</el-button
      >
      <el-button
        type="warning"
        v-hasPermi="['order:producManaga:producPlan:examinePlan']"
        :disabled="DelDisabled"
        @click="allExamine"
        >批量审核</el-button
      >
      <el-button
        type="warning"
        v-hasPermi="['order:producManaga:producPlan:revoke']"
        :disabled="ExamineDisabled"
        @click="revokeReview"
        >撤销审核</el-button
      >
      <el-button
        type="warning"
        v-hasPermi="['order:producManaga:producPlan:examinePlan']"
        :disabled="ExamineDisabled"
        @click="auditPlan"
        >审核计划</el-button
      >
      <el-button
        type="primary"
        :disabled="DelDisabled"
        v-hasPermi="['order:producManaga:producPlan:generate']"
        @click="getrkd"
        >生成成品入库单</el-button
      >
      <el-button
        type="primary"
        :disabled="DelDisabled"
        v-hasPermi="['order:producManaga:producPlan:finished']"
        @click="getFinished"
        >生成半成品入库单</el-button
      >
      <el-button
        type="info"
        :disabled="DelDisabled"
        v-hasPermi="['order:producManaga:producPlan:export']"
        @click="
          proxy.downloadPdf('/order/productPlan/productPlanPrint', {
            ...query,
            idStr: Ids.join(',')
          })
        "
        >导出</el-button
      >
      <el-button
        type="success"
        :disabled="DelDisabled"
        v-hasPermi="['order:producManaga:producPlan:push']"
        @click="pushData"
        >推送</el-button
      >
      <el-tabs v-model="query.planType" @tab-click="tabChange">
        <el-tab-pane label="生产计划" name="1"></el-tab-pane>
        <el-tab-pane label="样品计划" name="2"></el-tab-pane>
        <el-tab-pane label="备货计划" name="3"></el-tab-pane>
        <el-tab-pane label="成品改制" name="4"></el-tab-pane>
      </el-tabs>
      <!-- 生产计划 -->
      <el-table
        v-if="query.planType == '1'"
        v-loading="loading"
        stripe
        border
        :data="TableData"
        @selection-change="samplePlanChange"
        :height="maxHeight"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" width="70" type="index" />
        <el-table-column label="计划单号" prop="planNumber" width="180" />
        <el-table-column label="单据状态" align="center" width="100">
          <template #default="scope">
            <p-dictTag :options="plan_status" :value="scope.row.documentStatus" />
          </template>
        </el-table-column>
        <el-table-column label="客户名称" prop="customerName" width="150" />
        <el-table-column label="产品编码" prop="materialCode" width="150" />
        <el-table-column label="产品名称" prop="materialName" width="150" />
        <el-table-column label="规格型号" prop="specType" width="150" />
        <el-table-column label="订单数量" prop="planWeight" width="150" />
        <el-table-column label="商品行备注" prop="remark" width="150" />
        <el-table-column label="生成入库单据" prop="isDocumentName" width="150" />
        <el-table-column label="成品数量" prop="productNum" width="150" />
        <el-table-column label="半成品数量" prop="materialHalfNum" width="150" />
        <el-table-column label="交货时间" prop="deliveryDate" width="220" />
        <el-table-column label="单据日期" prop="createTime" width="220" />
        <el-table-column label="计划开工日期" prop="planStartWorkDate" width="150" />
        <el-table-column label="计划完工日期" prop="planEndWorkDate" width="150" />
        <el-table-column label="制单人" prop="createBy" width="150" />
        <el-table-column label="终止原因" prop="terminationReason" width="150" />
        <el-table-column label="销售订单号" prop="salesOrderNum" width="150" />
        <el-table-column label="推送状态" prop="isPushStatus" width="150">
          <template #default="scope">
            <p-dictTag :options="is_push_status" :value="scope.row.isPush" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-link
              type="primary"
              v-hasPermi="['order:producManaga:producPlan:edit']"
              text="修改"
              @click="edit(scope.row)"
            />
            <el-link
              type="primary"
              v-hasPermi="['order:producManaga:producPlan:query']"
              text="查看"
              @click="dxamine(scope.row)"
            />

            <el-link
              type="danger"
              v-hasPermi="['order:producManaga:producPlan:remove']"
              text="删除"
              @click="del(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 样品计划 -->
      <el-table
        v-loading="loading"
        v-if="query.planType == '2'"
        stripe
        border
        :data="TableData"
        @selection-change="samplePlanChange"
        :height="maxHeight"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" width="70" type="index" />
        <el-table-column label="计划单号" prop="planNumber" width="180" />
        <el-table-column label="单据状态" align="center" width="100">
          <template #default="scope">
            <p-dictTag :options="plan_status" :value="scope.row.documentStatus" />
          </template>
        </el-table-column>
        <el-table-column label="客户名称" prop="customerName" width="150" />
        <el-table-column label="产品编码" prop="materialCode" width="150" />
        <el-table-column label="产品名称" prop="materialName" width="150" />
        <el-table-column label="规格型号" prop="specType" width="150" />
        <el-table-column label="订单数量" prop="planWeight" width="150" />
        <el-table-column label="商品行备注" prop="remark" width="150" />
        <el-table-column label="生成入库单据" prop="isDocumentName" width="150" />
        <el-table-column label="成品数量" prop="productNum" width="150" />
        <el-table-column label="半成品数量" prop="materialHalfNum" width="150" />
        <el-table-column label="交货时间" prop="deliveryDate" width="220" />
        <el-table-column label="单据日期" prop="createTime" width="220" />
        <el-table-column label="计划开工日期" prop="planStartWorkDate" width="150" />
        <el-table-column label="计划完工日期" prop="planEndWorkDate" width="150" />
        <el-table-column label="制单人" prop="createBy" width="150" />
        <el-table-column label="终止原因" prop="terminationReason" width="150" />
        <el-table-column label="样品单号" prop="salesOrderNum" width="150" />
        <el-table-column label="推送状态" prop="isPushStatus" width="150">
          <template #default="scope">
            <p-dictTag :options="is_push_status" :value="scope.row.isPush" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-link
              type="primary"
              v-hasPermi="['order:producManaga:producPlan:edit']"
              text="修改"
              @click="edit(scope.row)"
            />
            <el-link
              type="primary"
              v-hasPermi="['order:producManaga:producPlan:query']"
              text="查看"
              @click="dxamine(scope.row)"
            />
            <el-link
              type="danger"
              v-hasPermi="['order:producManaga:producPlan:remove']"
              text="删除"
              @click="del(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 备货计划 -->
      <el-table
        v-loading="loading"
        v-if="query.planType == '3'"
        stripe
        border
        :data="TableData"
        @selection-change="samplePlanChange"
        :height="maxHeight"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" width="70" type="index" />
        <el-table-column label="计划单号" prop="planNumber" width="180" />
        <el-table-column label="单据状态" align="center" width="100">
          <template #default="scope">
            <p-dictTag :options="plan_status" :value="scope.row.documentStatus" />
          </template>
        </el-table-column>
        <el-table-column label="客户名称" prop="customerName" width="150" />
        <el-table-column label="产品编码" prop="materialCode" width="150" />
        <el-table-column label="产品名称" prop="materialName" width="150" />
        <el-table-column label="规格型号" prop="specType" width="150" />
        <el-table-column label="订单数量" prop="planWeight" width="150" />
        <el-table-column label="商品行备注" prop="remark" width="150" />
        <el-table-column label="生成入库单据" prop="isDocumentName" width="150" />
        <el-table-column label="成品数量" prop="productNum" width="150" />
        <el-table-column label="半成品数量" prop="materialHalfNum" width="150" />
        <el-table-column label="交货时间" prop="deliveryDate" width="220" />
        <el-table-column label="单据日期" prop="createTime" width="220" />
        <el-table-column label="计划开工日期" prop="planStartWorkDate" width="150" />
        <el-table-column label="计划完工日期" prop="planEndWorkDate" width="150" />
        <el-table-column label="制单人" prop="createBy" width="150" />
        <el-table-column label="终止原因" prop="terminationReason" width="150" />
        <el-table-column label="备货单号" prop="salesOrderNum" width="150" />
        <el-table-column label="推送状态" prop="isPushStatus" width="150">
          <template #default="scope">
            <p-dictTag :options="is_push_status" :value="scope.row.isPush" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-link
              type="primary"
              v-hasPermi="['order:producManaga:producPlan:edit']"
              text="修改"
              @click="edit(scope.row)"
            />
            <el-link
              type="primary"
              v-hasPermi="['order:producManaga:producPlan:query']"
              text="查看"
              @click="dxamine(scope.row)"
            />
            <el-link
              type="danger"
              v-hasPermi="['order:producManaga:producPlan:remove']"
              text="删除"
              @click="del(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 成品改制 -->
      <el-table
        v-loading="loading"
        v-if="query.planType == '4'"
        stripe
        border
        :data="TableData"
        @selection-change="samplePlanChange"
        :height="maxHeight"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" width="70" type="index" />
        <el-table-column label="计划单号" prop="planNumber" width="180" />
        <el-table-column label="单据状态" align="center" width="100">
          <template #default="scope">
            <p-dictTag :options="plan_status" :value="scope.row.documentStatus" />
          </template>
        </el-table-column>
        <el-table-column label="客户名称" prop="customerName" width="150" />
        <el-table-column label="产品编码" prop="materialCode" width="150" />
        <el-table-column label="产品名称" prop="materialName" width="150" />
        <el-table-column label="规格型号" prop="specType" width="150" />
        <el-table-column label="订单数量" prop="planWeight" width="150" />
        <el-table-column label="商品行备注" prop="remark" width="150" />
        <el-table-column label="生成入库单据" prop="isDocumentName" width="150" />
        <el-table-column label="成品数量" prop="productNum" width="150" />
        <el-table-column label="半成品数量" prop="materialHalfNum" width="150" />
        <el-table-column label="交货时间" prop="deliveryDate" width="220" />
        <el-table-column label="单据日期" prop="createTime" width="220" />
        <el-table-column label="计划开工日期" prop="planStartWorkDate" width="150" />
        <el-table-column label="计划完工日期" prop="planEndWorkDate" width="150" />
        <el-table-column label="制单人" prop="createBy" width="150" />
        <el-table-column label="终止原因" prop="terminationReason" width="150" />
        <el-table-column label="销售订单号" prop="salesOrderNum" width="150" />
        <el-table-column label="推送状态" prop="isPushStatus" width="150">
          <template #default="scope">
            <p-dictTag :options="is_push_status" :value="scope.row.isPush" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-link
              type="primary"
              v-hasPermi="['order:producManaga:producPlan:edit']"
              text="修改"
              @click="edit(scope.row)"
            />
            <el-link
              type="primary"
              v-hasPermi="['order:producManaga:producPlan:query']"
              text="查看"
              @click="dxamine(scope.row)"
            />

            <el-link
              type="danger"
              v-hasPermi="['order:producManaga:producPlan:remove']"
              text="删除"
              @click="del(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 创建 -->
    <p-XiaoheDialog :dialogVisible="isShow" :title="title" @close="close" width="60%">
      <template #body>
        <From ref="formRef" :title="title" :data="ruleForm" />
        <!-- 按钮 -->
        <Btn v-if="title != '查看'" :loading="BtnLoading" @submit="submit" @close="close" />
      </template>
    </p-XiaoheDialog>

    <!-- 终止弹窗 -->
    <p-XiaoheDialog :dialogVisible="endIsShow" :title="title" @close="close" width="20%">
      <template #body>
        <End ref="endRef" :title="title" :data="ruleForm" />
        <!-- 按钮 -->
        <Btn :loading="BtnLoading" @submit="endSubmit" @close="close" />
      </template>
    </p-XiaoheDialog>

    <!-- 审核弹窗 -->
    <p-XiaoheDialog :dialogVisible="examineIsShow" :title="title" @close="close" width="70%">
      <template #body>
        <AuditHistory :auditDoc="ruleForm.planNumber" perms="order:producManaga:producPlan:examine">
          <template #body>
            <From ref="formRef" :title="title" :data="ruleForm" />
            <div class="Btn" v-if="title == '审核计划'">
              <el-button type="danger" :loading="Btnloading" @click="yesAndNo(2)">不同意</el-button>
              <el-button type="success" :loading="Btnloading" @click="yesAndNo(1)">同意</el-button>
              <el-button type="inof" @click="close">取消</el-button>
            </div>
          </template>
        </AuditHistory>
      </template>
    </p-XiaoheDialog>
  </div>
</template>

<style lang="scss" scoped></style>
